<template>
  <div class="home">
    <!-- 头部导航 -->
    <header-nav ref="headerNav" />
    
    <!-- 主要内容区 -->
    <main class="main-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>
      
      <template v-else>
        <!-- 轮播图 -->
        <div class="banner-section">
          <el-carousel height="400px" :interval="5000" arrow="always">
            <el-carousel-item v-for="banner in banners" :key="banner.id">
              <!-- <router-link :to="banner.link"> -->
                <img 
                  :src="banner.image.startsWith('http') 
                    ? banner.image 
                    : `${baseURL}/uploads/${banner.image.replace(/^\/uploads\//, '')}`"
                  :alt="banner.name"
                  class="banner-image"
                />
              <!-- </router-link> -->
            </el-carousel-item>
          </el-carousel>
        </div>

        <!-- 主题区域@click="router.push(theme.link)" -->
        <div v-if="theme" class="theme-section">
          <div class="theme-header">
            <h1>{{ theme.name }}</h1>
            <p class="theme-description">{{ theme.description }}</p>
            <el-button type="primary" class="theme-button" >
              Hop To It
            </el-button>
          </div>
          
          <el-row :gutter="20" class="theme-products">
            <el-col 
              v-for="product in theme.products" 
              :key="product.id"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
            >
              <product-card :product="product" />
            </el-col>
          </el-row>
        </div>

        <!-- 热门商品 -->
        <div class="section">
          <div class="section-header">
            <h2>热门商品</h2>
            <el-button type="primary" text>查看更多</el-button>
          </div>
          <el-row :gutter="20">
            <el-col 
              v-for="product in hotProducts" 
              :key="product.id"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
            >
              <product-card :product="product" />
            </el-col>
          </el-row>
        </div>
      </template>
    </main>

    <!-- 页脚 -->
    <el-footer height="200px" class="footer">
      <div class="footer-content">
        <div class="footer-section">
          <h3>关于我们</h3>
          <p>StoryPlush 是一家专注于毛绒玩具的在线商城</p>
        </div>
        <div class="footer-section">
          <h3>联系方式</h3>
          <p>邮箱: contact@storyplush.com</p>
          <p>电话: 400-123-4567</p>
        </div>
        <div class="footer-section">
          <h3>快速链接</h3>
          <el-link>新品上市</el-link>
          <el-link>热卖商品</el-link>
          <el-link>品牌故事</el-link>
        </div>
        <div class="footer-section">
          <h3>关注我们</h3>
          <div class="social-links">
            <el-button :icon="Platform" circle />
            <el-button :icon="Platform" circle />
            <el-button :icon="Platform" circle />
          </div>
        </div>
      </div>
      <div class="footer-bottom">
        <p>© 2024 StoryPlush. All rights reserved.</p>
      </div>
    </el-footer>

    <!-- 返回顶部 -->
    <el-backtop :right="20" :bottom="20" />
  </div>
</template>

<script setup>
import { ref, onMounted, onActivated, reactive, inject } from 'vue'
import HeaderNav from '../components/HeaderNav.vue'
import ProductCard from '../components/ProductCard.vue'
import { Platform } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from '../utils/axios'
import { useRouter } from 'vue-router'
import { useDataFetching } from '../composables/useDataFetching'
import { useImageLoader } from '../composables/useImageLoader'
import { storeToRefs } from 'pinia'
import { useProductStore } from '../stores/product'

const baseURL = import.meta.env.VITE_API_URL || 'http://localhost:5000'
const banners = ref([])
const hotProducts = ref([])
const newProducts = ref([])
const loading = ref(true)
const error = ref(null)
const bannerErrors = reactive({})
const theme = ref(null)
const router = useRouter()
const headerNavMethods = inject('headerNavMethods')
const productStore = useProductStore()
const { preloadedProducts } = storeToRefs(productStore)

const handleBannerError = (error, banner) => {
  console.error('Banner load error:', error);
  console.log('Failed banner URL:', banner.image);
  bannerErrors[banner.id] = true;
};

// 使用数据获取hook
const { 
  data: hotProductsData,
  loading: productsLoading,
  fetch: fetchHotProducts
} = useDataFetching(
  () => axios.get('/api/products/hot'),
  {
    cacheKey: 'hot_products',
    cacheDuration: 5 * 60 * 1000, // 5分钟缓存
    immediate: false // 不立即加载，等待预加载数据
  }
)

// 使用图片加载hook
const { imageErrors, handleImageError, preloadImages } = useImageLoader()

const loadData = async () => {
  try {
    loading.value = true
    const { data } = await axios.get('/api/home')
    
    // 获取轮播图数据
    const bannersResponse = await axios.get('/api/banners')
    banners.value = bannersResponse.data.map(banner => ({
      ...banner,
      image: banner.image?.startsWith('http') 
        ? banner.image 
        : `${baseURL}/uploads/${banner.image.replace(/^\/uploads\//, '')}`
    }))

    // 处理热门商品数据
    hotProducts.value = Array.isArray(data.hotProducts) ? data.hotProducts : []
    newProducts.value = Array.isArray(data.newProducts) ? data.newProducts : []
    
    // 处理图片路径
    hotProducts.value = hotProducts.value.map(product => ({
      ...product,
      image: product.image?.startsWith('http') 
        ? product.image 
        : `${baseURL}${product.image}`
    }))
    
    newProducts.value = newProducts.value.map(product => ({
      ...product,
      image: product.image?.startsWith('http') 
        ? product.image 
        : `${baseURL}${product.image}`
    }))
    
    if (data.theme) {
      theme.value = {
        ...data.theme,
        image: data.theme.image.startsWith('http')
          ? data.theme.image
          : `${baseURL}${data.theme.image}`,
        products: data.theme.products.map(product => ({
          ...product,
          image: product.image.startsWith('http')
            ? product.image
            : `${baseURL}${product.image}`
        }))
      }
    }
  } catch (err) {
    console.error('Error loading data:', err)
    error.value = err
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载和激活时加载数据
onMounted(() => {
  loadData()
  // 设置 HeaderNav 的引用
  headerNavMethods.value = headerNavMethods.value
  if (banners.value) {
    preloadImages(banners.value.map(b => b.image))
  }
})
</script>

<style scoped>
.home {
  min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  max-width: 1200px;
  margin: 60px auto 0;
  padding: 20px;
}

.banner-section {
  margin-bottom: 30px;
}

.section {
  margin-bottom: 40px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.footer {
  background-color: #fff;
  padding: 40px 0 20px;
  margin-top: 40px;
}

.footer-content {
  max-width: 1200px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 40px;
  padding: 0 20px;
}

.footer-section h3 {
  margin: 0 0 15px;
  font-size: 18px;
  color: #333;
}

.footer-section p {
  margin: 8px 0;
  color: #666;
}

.footer-section .el-link {
  display: block;
  margin: 8px 0;
}

.social-links {
  display: flex;
  gap: 10px;
}

.footer-bottom {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
  color: #999;
}

@media (max-width: 768px) {
  .main-content {
    padding: 10px;
  }
  
  .section-header h2 {
    font-size: 20px;
  }
  
  .footer-content {
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
  }
}

@media (max-width: 480px) {
  .footer-content {
    grid-template-columns: 1fr;
  }
}

/* 添加加载状态样式 */
.loading-container {
  padding: 20px;
  margin-top: 60px;
}

.banner-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 20px;
  margin-top: 10px;
}

/* 自定义轮播图箭头样式 */
:deep(.el-carousel__arrow) {
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 50%;
  width: 40px;
  height: 40px;
}

:deep(.el-carousel__arrow:hover) {
  background-color: rgba(0, 0, 0, 0.5);
}

.theme-section {
  margin: 60px 0;
  padding: 40px;
  background-color: #f0f9ff;
  border-radius: 12px;
}

.theme-header {
  text-align: center;
  max-width: 800px;
  margin: 0 auto 40px;
}

.theme-header h1 {
  font-size: 36px;
  color: #333;
  margin-bottom: 20px;
}

.theme-description {
  font-size: 18px;
  color: #666;
  line-height: 1.6;
  margin-bottom: 30px;
}

.theme-button {
  font-size: 18px;
  padding: 12px 30px;
  border-radius: 25px;
}

.theme-products {
  margin-top: 40px;
}

@media (max-width: 768px) {
  .theme-section {
    padding: 20px;
    margin: 30px 0;
  }
  
  .theme-header h1 {
    font-size: 28px;
  }
  
  .theme-description {
    font-size: 16px;
  }
}
</style> 